#include "server.h"

// 构造函数
Server::Server(QObject *parent) : QObject(parent), chatServer(new QTcpServer(this))
{
    allClients = QVector<QTcpSocket*>(); // 初始化客户端数组
}

// 启动服务器
void Server::startServer()
{
    // 限制最大待连接客户端数为 10 个
    chatServer->setMaxPendingConnections(10);
    connect(chatServer, &QTcpServer::newConnection, this, &Server::newClientConnection);

    // 持续监听 8001 端口
    if (chatServer->listen(QHostAddress::Any, 8001)) {
        qDebug() << "服务器已启动，正在监听 8001 端口。";
        emit serverStarted(); // 发出服务器启动的信号
    } else {
        qDebug() << "服务器启动失败。错误信息: " + chatServer->errorString();
        emit serverError(chatServer->errorString()); // 发送错误信号
    }
}

// 向所有客户端发送消息
void Server::sendMessageToClients(const Message &message) {
    QJsonDocument doc(message.toJson());
    QByteArray messageData = doc.toJson();

    for (QTcpSocket* client : allClients) {
        if (client->isOpen() && client->isWritable()) {
            client->write(messageData); // 发送序列化后的消息
        }
    }
}

// 处理新的客户端连接
void Server::newClientConnection()
{
    QTcpSocket* client = chatServer->nextPendingConnection();
    QString ipAddress = client->peerAddress().toString();
    int port = client->peerPort();

    // 连接客户端的信号到相应的槽函数
    connect(client, &QTcpSocket::disconnected, this, &Server::socketDisconnected);
    connect(client, &QTcpSocket::readyRead, this, &Server::socketReadyRead);
    connect(client, &QTcpSocket::stateChanged, this, &Server::socketStateChanged);

    allClients.push_back(client); // 存储新客户端
    qDebug() << "客户端连接成功: " + ipAddress + ":" + QString::number(port);
}

// 处理客户端断开连接
void Server::socketDisconnected()
{
    QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());
    if (client) {
        QString socketIpAddress = client->peerAddress().toString();
        int port = client->peerPort();
        qDebug() << "客户端断开连接: " + socketIpAddress + ":" + QString::number(port);

        allClients.removeOne(client); // 从 allClients 中移除断开的客户端

        // 安全删除客户端对象
        client->deleteLater();
    }
}

// 处理客户端发送消息
void Server::socketReadyRead()
{
    QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());
    if (client) {
        while (client->canReadLine()) {
            QByteArray data = client->readAll(); // 读取客户端发送的数据
            QJsonDocument doc = QJsonDocument::fromJson(data);
            if (doc.isObject()) {
                Message message = Message::fromJson(doc.object()); // 从 JSON 对象转换为 Message 对象
                qDebug() << "收到消息: " + message.getContent() + " 来自: " + message.getSenderId();
                sendMessageToClients(message); // 将消息转发给所有连接的客户端
            }
        }
    }
}

// 处理客户端网络状态变化
void Server::socketStateChanged(QAbstractSocket::SocketState state)
{
    QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());
    if (client) {
        QString socketIpAddress = client->peerAddress().toString();
        int port = client->peerPort();
        QString desc;

        // 根据新状态打印相应消息
        switch (state) {
        case QAbstractSocket::UnconnectedState:
            desc = "套接字未连接。";
            break;
        case QAbstractSocket::HostLookupState:
            desc = "套接字正在进行主机名查找。";
            break;
        case QAbstractSocket::ConnectingState:
            desc = "套接字已开始建立连接。";
            break;
        case QAbstractSocket::ConnectedState:
            desc = "已建立连接。";
            break;
        case QAbstractSocket::BoundState:
            desc = "套接字已绑定到地址和端口。";
            break;
        case QAbstractSocket::ClosingState:
            desc = "套接字即将关闭（数据可能仍在等待写入）。";
            break;
        case QAbstractSocket::ListeningState:
            desc = "仅供内部使用。";
            break;
        default:
            desc = "未知状态。";
            break;
        }

        qDebug() << "套接字状态改变 (" + socketIpAddress + ":" + QString::number(port) + "): " + desc;
    }
}

void Server::stopServer()
{
    // 先断开所有客户端连接
    foreach (QTcpSocket *client, allClients) {
        client->disconnect(); // 断开信号连接
        client->close(); // 关闭 socket
        client->deleteLater(); // 安全删除客户端 socket
    }
    allClients.clear(); // 清空客户端列表

    // 关闭服务器
    chatServer->close();
    qDebug() << "服务器已停止。";
}
